<?php

/**
 * Description of FileGeneratorAbstract
 *
 * @author David Safranek <safrad@rosada.cz>
 */
abstract class FileGeneratorAbstract {

	/**
	 * path
	 * @var string target
	 */
	private $target;

	/**
	 * @var array
	 */
	private $sources;
	
	/**
	 * path
	 * @var string target
	 */
	private $command;

		public function getTarget() {
		return $this->target;
	}

	public function getSources() {
		return $this->sources;
	}

	public function setTarget($target) {
		$this->target = $target;
		return $this;
	}

	public function setSources($sources) {
		$this->sources = $sources;
		return $this;
	}

	public function addSource($source) {
		$this->sources[] = $source;
		return $this;
	}

	public function getCommand() {
		return $this->command;
	}

	public function setCommand($command) {
		$this->command = $command;
		return $this;
	}

	public function targetDate() {
		if (!file_exists($this->getTarget())) {
			return 0;
		} else {
			return filemtime($this->getTarget());
		}
	}
	
	/**
	 * 
	 * @return int the newest time the source file was last modified
	 */
	public function newestFileDate() {
		$result = 0;
		foreach ($this->sources as $source) {
			$dateTime = filemtime($source);
			if ($dateTime > $result) {
				$result = $dateTime;
			}
		}
		return $result;
	}
	
	/**
	 * Update target file
	 * @return boolean
	 * @throws Exception
	 */
	public function needGenerate() {
		$lastDate = $this->targetDate();
		if (($lastDate == 0) or ($this->newestFileDate() > $lastDate)) {
			return TRUE;
		}
		return FALSE;
	}

	/**
	 * @return void
	 */
	public function generate() {
		if ($this->needGenerate()) {
			$this->forceGenerate();
		}
	}
	
	/**
	 * @return void
	 */
	abstract protected function forceGenerate();

	/**
	 * Return target file data
	 * @return string
	 */
	public function output() {
		$this->generate();
		return file_get_contents($this->getTarget());
	}
}
